// pages/mine/mine.js
import MineModel from './model'
let model = new MineModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    history: [],
    isLogin: false,
    offset: 0,
    limit: 5
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    wx.getStorage({
      key: 'userinfo',
      success: (res) => {
        this.setData({
          userInfo: res.data,
          isLogin: true
        })
        // 获取历史记录
        let data = {
          offset: this.data.offset,
          limit: this.data.limit
        };
        model.getHistory({
          obj: this,
          data,
          refresh: true
        })
      }
    });
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    // 获取历史记录
    let data = {
      offset: 0,
      limit: 5
    };

    model.getHistory({
      obj: this,
      data,
      refresh: true
    }).then(res => {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 获取历史记录
    let data = {
      offset: this.data.offset + this.data.limit,
      limit: this.data.limit
    };
    model.getHistory({
      obj: this,
      data,
      refresh: false
    })
  },
  // 用户登录

  // 授权
  bindGetUserInfo(e) {
    if (wx.getStorageSync('loginSessionKey')) return false;
    model.code2Session().then(res => {
      if (wx.getStorageSync('userinfo')) return;
      let userinfo = e.detail.userInfo;
      // 未通过授权
      if (!userinfo) return;
      // 通过授权，发送userinfo到服务器
      userinfo.loginSessionKey = wx.getStorageSync('loginSessionKey');
      model.postUserinfo({
        obj: this,
        data: userinfo,
      }).then(res => {
        // 获取观看记录
        let data = {
          offset: 0,
          limit: 5
        };
        model.getHistory({
          obj: this,
          data,
          refresh: true
        })
      })
    })

  },










  // 点击开始
  tStart() {
    let stime = new Date().getTime();
    this.data.stime = stime;
  },
  // 点击结束
  tEnd() {
    let etime = new Date().getTime();
    let num = etime - this.data.stime;
    let color = this.getColor(num);
    console.log(color);
    this.setData({
      color
    })
  },
  // 通过差值生成颜色
  getColor(num) {
    num = num / 500;
    let color = "#000";
    if (num <= 1) {
      color = "#ff0000";
    } else if (num <= 3) {
      color = "#00ff00";
    } else if (num <= 5) {
      color = "#0000ff";
    } else {
      color = "#23ac5a";
    }
    return color;
  },
  changeColor(e) {
    console.log(e);
    console.log(e.currentTarget.dataset);

  }
})